package com.register.web;


import com.alibaba.fastjson.JSONObject;
import com.register.pojo.User;
import com.register.service.RegistorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class RegisterController {
    @Autowired
    private RegistorService registorService;

    /**
     * 获取ticket
     *
     * @param request
     * @param response
     * @param backUrl
     * @throws IOException
     */
    @RequestMapping("getTicket")
    public void getTicket(HttpServletRequest request, HttpServletResponse response, String backUrl) throws IOException {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies
                ) {
            if (cookie.getName().equals("ticket")) {
                response.sendRedirect(backUrl + "?ticket=" + cookie.getValue());
                return;
            }
        }
        response.sendRedirect("/registor/login.jsp");

    }

    /**
     * 验证ticket是否有效
     *
     * @param ticket
     * @return
     */
    @RequestMapping("verifyTicket")
    public JSONObject verifyTicket(HttpServletRequest request, String ticket) {
        User user = registorService.verifyTicket(ticket);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user", user);

        if (user != null) {
            jsonObject.put("status", "success");
        } else {
            jsonObject.put("status", "error");
        }

        return jsonObject;
    }

    /**
     * 退出
     *
     * @param request
     */
    @RequestMapping("exit")
    public void exit(HttpServletRequest request,HttpServletResponse response,String backUrl) throws IOException {
        Cookie[] cookies = request.getCookies();
        String ticket = "";
        for (Cookie cookie :
                cookies) {
            if ("ticket".equals(cookie.getName()))
                ticket = cookie.getValue();
        }
        registorService.deleteUser(ticket);
        response.sendRedirect(backUrl);
    }
}
